package redisdb

import (
	"github.com/go-redis/redis"
	"time"
)

const (
	addr            = "127.0.0.1:6379"
	Password        = ""
	dB              = 0
	network         = "tcp"
	maxRetries      = 10
	minRetryBackoff = time.Millisecond * 8
	MaxRetryBackoff = time.Millisecond * 512
	readTimeout     = time.Second * 3
	writeTimeout    = time.Second * 3
	poolSize        = 20
	minIdleConns    = 1
	maxConnAge      = time.Second * 60
	PoolTimeout     = time.Second * 4
	idleTimeout     = time.Minute * 3
)

type Getter interface {
	DbGet() *redis.Client
	Set(k string, v interface{}, t ...time.Duration) error
	Get(k string) (string, error)
	Del(ks ...string) (int64, error)
	Exists(ks ...string) (int64, error)
	HExists(k, f string) (bool, error)
	HSet(k, f string, v interface{}) bool
	HGet(k, f string) (string, error)
	HDel(k string, fs ...string) (int64, error)
	HGetAll(key string) (map[string]string, error)
	Keys(pattern string) ([]string, error)
	CloseDb() error
	Expire(pattern string, expiration time.Duration) (bool, error)
}

type RedisDb struct {
	Db *redis.Client
}

func New() (*RedisDb, error) {
	r := &RedisDb{}
	r.Db = redis.NewClient(&redis.Options{
		Addr:            addr,
		Password:        Password,
		DB:              dB,
		Network:         network,
		MaxRetries:      maxRetries,
		MinRetryBackoff: minRetryBackoff,
		MaxRetryBackoff: MaxRetryBackoff,
		ReadTimeout:     readTimeout,
		WriteTimeout:    writeTimeout,
		PoolSize:        poolSize,
		MinIdleConns:    minIdleConns,
		MaxConnAge:      maxConnAge,
		PoolTimeout:     PoolTimeout,
		IdleTimeout:     idleTimeout,
	})
	if e := r.Db.Ping().Err(); e != nil {
		return nil, e
	}
	return r, nil
}
